/**
 * @Title: FileServiceImpl
 * @Package cn.com.yiqi.wsc.service.file.impl
 * @Description: TODO
 * Copyright: Copyright (c) 2016
 * Company: 成都壹柒互动科技有限公司
 * @author 会员系统组-胥钰淋
 * @date 2017/3/1 11:15
 * @version V1.0
 */
package cn.com.yiqi.wsc.service.file.impl;

import cn.com.artemis.framework.service.file.utils.QiniuUploadManagerSingleton;
import cn.com.yiqi.wsc.dao.file.FileDao;
import cn.com.yiqi.wsc.dao.file.entity.FileEntity;
import cn.com.yiqi.wsc.service.file.FileService;
import cn.com.yiqi.wsc.service.file.dataobject.FileDO;
import cn.com.yiqi.wsc.service.file.dataobject.QiniuConfig;
import cn.com.yiqi.wsc.util.SnowflakeIdWorker;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 *
 *@ClassName: FileServiceImpl
 * @Description: TODO
 * @author 会员系统组-胥钰淋
 * @date 2017/3/1 11:15
 *
 */
@Service
public class FileServiceImpl implements FileService {

    private Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);

    @Autowired
    private QiniuConfig qiniuConfig;
    @Autowired
    private FileDao fileDao;

    //表单字段常亮
    public static final String FORM_FIELDS = "form_fileds";

    public static final String FILE_FIELDS = "file_fields";

    private static final int MAXSIZE  = 2000000;

    /**
     * 处理上传内容
     * @param request
     * @return
     */
    public Map<String, Object> initFields(HttpServletRequest request) {

        Map<String, Object> map = new HashMap<>();

        //第一步：判断request
        boolean isMultipart  = ServletFileUpload.isMultipartContent(request);

        //第二部：解析request
        if (isMultipart) {

            //创建factory
            FileItemFactory factory = new DiskFileItemFactory();

            //创建一个文件上传句柄
            ServletFileUpload upload = new ServletFileUpload(factory);

            upload.setHeaderEncoding("UTF-8");

            upload.setSizeMax(MAXSIZE);

            //FileItem
            List<FileItem> items = null;

            //解析请求
            try {
                items = upload.parseRequest(request);
            } catch (FileUploadException e) {
                //TODO
                e.printStackTrace();
            }

            //第三部：处理uploaded items
            if (items != null && items.size() > 0) {

                Iterator<FileItem> itr = items.iterator();

                //文件域对象
                List<FileItem> list = new ArrayList<>();

                //表单字段
                Map<String, String> fields = new HashMap<>();

                while (itr.hasNext()) {

                    FileItem item = itr.next();

                    //处理所有表单元素和文件域表单元素
                    if (item.isFormField()) {
                        //表单元素
                        String name = item.getFieldName();
                        String value = item.getString();
                        fields.put(name, value);
                    }
                    else {
                        //文件域表单元素
                        list.add(item);
                    }
                }
                map.put(FORM_FIELDS, fields);
                map.put(FILE_FIELDS, list);
            }
        }
        return map;
    }

    @Override
    public List<FileDO> upload(HttpServletRequest request) {
        //初始化表单元素
        Map<String, Object> filedsMap = new HashMap<>();
        filedsMap = this.initFields(request);
        //上传
        List<FileItem> fileItemList = (List<FileItem>) filedsMap.get(FILE_FIELDS);
        List<FileDO> list = new ArrayList<>();
        if (null != fileItemList) {
            for (FileItem file:
                 fileItemList) {
                try {
                    list.add(saveFileToQinui(file));
                } catch (IOException e) {
                    logger.error("--- 图片处理异常 ---", e.getMessage());
                }
            }
        }
        return list;
    }

    private FileDO saveFileToQinui(FileItem item) throws IOException {
        FileDO fileDO = new FileDO();
        //密钥配置
        Auth auth = Auth.create(qiniuConfig.getACCESS_KEY(), qiniuConfig.getSECRET_KEY());

        //创建上传对象
        UploadManager uploadManager = QiniuUploadManagerSingleton.getInstance();

        //获取上传文件名称
        String fileName = item.getName();

        //获取上传文件扩展名
        String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();

        SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0, 0);

        String fid = idWorker.nextId() + "";

        String newFileName = fid + "." +  fileExt;

        InputStream input = item.getInputStream();

        byte[] bytes = IOUtils.toByteArray(input);

        Response res = uploadManager.put(bytes, newFileName,  auth.uploadToken(qiniuConfig.getBUCKET_NAME()));

        fileDO.setId(fid);
        fileDO.setExt(fileExt);
        fileDO.setName(fileName);
        if (!res.isOK()) {
            fileDO.setSuccess(false);
        }
        else {
            FileEntity fileEntity = new FileEntity();
            fileEntity.setName(fid);
            fileEntity.setRealName(fileName);
            fileEntity.setExt(fileExt);
            fileEntity.setUploadTime(new Date());
            fileDao.insert(fileEntity);
            fileDO.setSuccess(true);
        }
        return fileDO;
    }
}
